#ifndef SERVER_H
#define SERVER_H

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QMap>
#include <QString>
#include <QTime>
#include <QList>
#include <QNetworkInterface>
#include <QLinkedList>

#include "Inc/device.h"

#define PORT 8887

class Server : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QList<Device *> deviceList READ getDeviceList NOTIFY devicesChanged)
    Q_PROPERTY(QString host_ip READ getHostIp NOTIFY serverStatusChanged)
    Q_PROPERTY(QString gateway_ip READ getGatewayIp NOTIFY serverStatusChanged)
    Q_PROPERTY(quint16 port READ getPort NOTIFY serverStatusChanged)
    Q_PROPERTY(bool server_running READ isServerRunning NOTIFY serverStatusChanged)
    Q_PROPERTY(int tcp_clients_count READ getTcpClientsCount NOTIFY clientsChanged)

public:
    explicit Server(QObject *parent = nullptr);
    ~Server();

    QList<Device *> getDeviceList() const { return device_list; }

    quint16 getPort() const { return port; }
    bool isServerRunning() const { return server_running; }
    QString getHostIp() const { return host_ip; }
    QString getGatewayIp() const { return gateway_ip; }
    int getTcpClientsCount() const { return tcp_clients_count; }
    // Q_INVOKABLE void measureAt(quint8 deviceId, uint16_t freq);
    Q_INVOKABLE void newMeasure(quint8 deviceId);
    void sendToPCs(const QByteArray &data);

signals:
    void devicesChanged();
    void serverStatusChanged();
    void clientsChanged();

private slots:
    void onNewConnection();
    void onReadyRead();
    void onDisconnected();

private:
    // void sendToClient(QTcpSocket *client, const QByteArray &data);
    QTcpServer *server;
    QList<QTcpSocket *> pcs;
    QMap<QTcpSocket *, quint8> clients;
    QList<Device *> device_list;
    QMap<quint8, Device *> device_map;
    QString host_ip;
    QString gateway_ip;
    quint16 port;
    int tcp_clients_count;
    bool server_running;
};

#endif // SERVER_H
